package cn.itcast.user.web;

import cn.itcast.user.config.PatternProperties;
import cn.itcast.user.pojo.User;
import cn.itcast.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
// @RefreshScope  // 第一种方式
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private PatternProperties properties;

    // @Value("${pattern.dateformat}")
    // private String dateformat;

    @GetMapping("prop")
    public PatternProperties properties() {
        return properties;
    }


    @GetMapping("now")
    public String now() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(properties.getDateformat()));
    }

    /**
     * 路径： /user/110
     *
     * @param id 用户id
     * @return 用户
     */
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id,
                          @RequestHeader(value = "Truth", required = false) String truth,
                          @RequestHeader(value = "name", required = false) String name) throws InterruptedException {
        if (id == 1) {
            // id为1时, 触发慢调用
            Thread.sleep(60);
        } else if (id == 2) {
            // 测试熔断降级的异常比例 | 异常数
            throw new RuntimeException("故意出错, 触发熔断");
        }

        log.info("Truth : {}", truth);
        log.info("name : {}", name);
        return userService.queryById(id);
    }
}
